.TH std::as_const 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::as_const \- std::as_const

.SH Synopsis
   Defined in header <utility>
   template< class T >                                       \fB(1)\fP \fI(since C++17)\fP
   constexpr std::add_const_t<T>& as_const( T& t ) noexcept;
   template< class T >                                       \fB(2)\fP \fI(since C++17)\fP
   void as_const( const T&& ) = delete;

   1) Forms lvalue reference to const type of t.
   2) const rvalue reference overload is deleted to disallow rvalue arguments.

.SH Possible implementation

   template<class T>
   constexpr std::add_const_t<T>& as_const(T& t) noexcept
   {
       return t;
   }

.SH Notes

   Feature-test macro  Value    Std      Feature
   __cpp_lib_as_const 201510L \fI(C++17)\fP std::as_const

.SH Example


// Run this code

 #include <cassert>
 #include <string>
 #include <type_traits>
 #include <utility>

 int main()
 {
     std::string mutableString = "Hello World!";
     auto&& constRef = std::as_const(mutableString);

     mutableString.clear(); // OK
 //  constRef.clear(); // Error: 'constRef' is 'const' qualified,
                       //        but 'clear' is not marked const

     assert(&constRef == &mutableString);
     assert(&std::as_const(mutableString) == &mutableString);

     using ExprType = std::remove_reference_t<decltype(std::as_const(mutableString))>;

     static_assert(std::is_same_v<std::remove_const_t<ExprType>, std::string>,
                   "ExprType should be some kind of string.");
     static_assert(!std::is_same_v<ExprType, std::string>,
                   "ExprType shouldn't be a mutable string.");
 }

.SH See also

   is_const              checks if a type is const-qualified
   \fI(C++11)\fP               \fI(class template)\fP
   add_cv
   add_const
   add_volatile          adds const and/or volatile specifiers to the given type
   \fI(C++11)\fP               \fI(class template)\fP
   \fI(C++11)\fP
   \fI(C++11)\fP
   remove_cv
   remove_const
   remove_volatile       removes const and/or volatile specifiers from the given type
   \fI(C++11)\fP               \fI(class template)\fP
   \fI(C++11)\fP
   \fI(C++11)\fP
   ranges::as_const_view converts a view into a constant_range
   views::as_const       \fI(class template)\fP (range adaptor object)
   (C++23)
